import { CallHandler, ExecutionContext, NestInterceptor, RequestTimeoutException } from "@nestjs/common";
import { catchError, Observable, throwError, timeout, TimeoutError } from "rxjs";

class TimeoutInterceptor implements NestInterceptor {
    constructor(private readonly timeout: number = 10000) {
        console.log('TimeoutInterceptor');
    }

    intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
        return next.handle().pipe(
            timeout(this.timeout), 
            catchError((err) => {
            if (err instanceof TimeoutError) {
                console.log('TimeoutInterceptor: TimeoutError');
                return throwError(() => new RequestTimeoutException('请求超时'));
            }
                return throwError(() => err);
            }),
        );
    }
}

export default TimeoutInterceptor;